import React, { useState, useEffect } from 'react'
import { Plus, MessageCircle, Trash2, Calendar, ChevronDown } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { ChatService } from '@/services/chatService'

interface Conversation {
  id: string
  title: string
  lastMessage: string
  timestamp: Date
  messageCount: number
  chatMode?: string
}

interface ConversationListProps {
  currentConversationId?: string
  onSelectConversation: (conversationId: string, chatMode?: string) => void
  onNewConversation: () => void
  onConversationUpdate?: (conversationId: string, lastMessage: string) => void
  userId: number
}

export function ConversationList({
  currentConversationId,
  onSelectConversation,
  onNewConversation,
  onConversationUpdate,
  userId
}: ConversationListProps) {
  const [conversations, setConversations] = useState<Conversation[]>([])
  const [isLoading, setIsLoading] = useState(false)
  const [displayedConversations, setDisplayedConversations] = useState<Conversation[]>([])
  const [currentPage, setCurrentPage] = useState(1)
  const [hasMore, setHasMore] = useState(false)
  const itemsPerPage = 10
  
  const chatService = ChatService.getInstance()

  // 从后端API获取对话列表
  useEffect(() => {
    loadConversations()
  }, [userId])

  // 监听对话更新事件
  useEffect(() => {
    const handleConversationsUpdated = () => {
      loadConversations()
    }

    const handleUpdateConversation = (event: CustomEvent) => {
      const { conversationId, lastMessage, timestamp } = event.detail
      
      setConversations(prev => {
        const existingIndex = prev.findIndex(conv => conv.id === conversationId)
        
        if (existingIndex >= 0) {
          // 更新现有对话
          const updatedConversations = [...prev]
          updatedConversations[existingIndex] = {
            ...updatedConversations[existingIndex],
            lastMessage,
            timestamp: new Date(timestamp)
          }
          // 将更新的对话移到顶部
          const [updatedConv] = updatedConversations.splice(existingIndex, 1)
          return [updatedConv, ...updatedConversations]
        } else {
          // 创建新对话并添加到顶部
          const newConversation: Conversation = {
            id: conversationId,
            title: lastMessage.length > 30 ? lastMessage.substring(0, 30) + '...' : lastMessage,
            lastMessage,
            timestamp: new Date(timestamp),
            messageCount: 1
          }
          return [newConversation, ...prev]
        }
      })
    }

    window.addEventListener('conversationsUpdated', handleConversationsUpdated)
    window.addEventListener('updateConversation', handleUpdateConversation as EventListener)
    
    return () => {
      window.removeEventListener('conversationsUpdated', handleConversationsUpdated)
      window.removeEventListener('updateConversation', handleUpdateConversation as EventListener)
    }
  }, [userId])

  const loadConversations = async () => {
    setIsLoading(true)
    try {
      // 从后端API获取对话列表
      const apiConversations = await chatService.getUserConversations(userId)
      const conversations = apiConversations.map((conv: any) => ({
        id: conv.id.toString(),
        title: conv.title,
        lastMessage: conv.lastMessage,
        timestamp: new Date(conv.timestamp),
        messageCount: conv.messageCount,
        chatMode: conv.chatMode || 'normal'
      }))
      setConversations(conversations)
      setCurrentPage(1)
      updateDisplayedConversations(conversations, 1)
    } catch (error) {
      console.error('Error loading conversations:', error)
      // 如果API调用失败，尝试从localStorage加载
      try {
        const saved = localStorage.getItem('conversations')
        if (saved) {
          const parsed = JSON.parse(saved)
          const conversations = parsed.map((conv: any) => ({
            ...conv,
            timestamp: new Date(conv.timestamp)
          }))
          setConversations(conversations)
          setCurrentPage(1)
          updateDisplayedConversations(conversations, 1)
        }
      } catch (localError) {
        console.error('Error loading from localStorage:', localError)
      }
    } finally {
      setIsLoading(false)
    }
  }

  const updateDisplayedConversations = (allConversations: Conversation[], page: number) => {
    const startIndex = 0
    const endIndex = page * itemsPerPage
    const displayed = allConversations.slice(startIndex, endIndex)
    setDisplayedConversations(displayed)
    setHasMore(endIndex < allConversations.length)
  }

  const loadMore = () => {
    const nextPage = currentPage + 1
    setCurrentPage(nextPage)
    updateDisplayedConversations(conversations, nextPage)
  }

  const addOrUpdateConversation = (conversationId: string, lastMessage: string) => {
    const existingIndex = conversations.findIndex(conv => conv.id === conversationId)
    
    if (existingIndex >= 0) {
      // 更新现有对话
      const updated = [...conversations]
      updated[existingIndex] = {
        ...updated[existingIndex],
        lastMessage: lastMessage.slice(0, 50) + (lastMessage.length > 50 ? '...' : ''),
        timestamp: new Date(),
        messageCount: updated[existingIndex].messageCount + 1
      }
      setConversations(updated)
      updateDisplayedConversations(updated, currentPage)
      // 同时保存到localStorage作为备份
      localStorage.setItem('conversations', JSON.stringify(updated))
    } else {
      // 添加新对话
      const newConversation: Conversation = {
        id: conversationId,
        title: `对话 ${conversationId}`,
        lastMessage: lastMessage.slice(0, 50) + (lastMessage.length > 50 ? '...' : ''),
        timestamp: new Date(),
        messageCount: 1
      }
      const updated = [newConversation, ...conversations]
      setConversations(updated)
      updateDisplayedConversations(updated, currentPage)
      // 同时保存到localStorage作为备份
      localStorage.setItem('conversations', JSON.stringify(updated))
    }
  }

  const deleteConversation = (conversationId: string) => {
    const filtered = conversations.filter(conv => conv.id !== conversationId)
    setConversations(filtered)
    updateDisplayedConversations(filtered, currentPage)
    // 同时保存到localStorage作为备份
    localStorage.setItem('conversations', JSON.stringify(filtered))
    
    // 如果删除的是当前对话，创建新对话
    if (currentConversationId === conversationId) {
      onNewConversation()
    }
  }

  const formatTimestamp = (timestamp: Date) => {
    const now = new Date()
    const diff = now.getTime() - timestamp.getTime()
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))
    
    if (days === 0) {
      return timestamp.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      })
    } else if (days === 1) {
      return '昨天'
    } else if (days < 7) {
      return `${days}天前`
    } else {
      return timestamp.toLocaleDateString('zh-CN')
    }
  }

  // 暴露方法给父组件使用
  React.useEffect(() => {
    if (onConversationUpdate) {
      // 这里可以通过props传递方法引用
    }
  }, [onConversationUpdate])

  return (
    <Card className="flex-1 flex flex-col m-4 rounded-lg overflow-hidden">
      <CardHeader className="pb-3">
        <div className="flex items-center justify-between">
          <CardTitle className="text-lg flex items-center gap-2">
            <MessageCircle className="w-5 h-5" />
            对话历史
          </CardTitle>
          <Button
            onClick={onNewConversation}
            size="sm"
            className="flex items-center gap-2"
          >
            <Plus className="w-4 h-4" />
            新对话
          </Button>
        </div>
      </CardHeader>
      
      <CardContent className="flex-1 p-0 flex flex-col min-h-0">
        <div className="flex-1 px-4 pb-2 overflow-y-auto">
          {isLoading ? (
            <div className="flex items-center justify-center py-8 text-muted-foreground">
              加载中...
            </div>
          ) : conversations.length === 0 ? (
            <div className="flex flex-col items-center justify-center py-8 text-muted-foreground">
              <MessageCircle className="w-12 h-12 mb-4 opacity-50" />
              <p className="text-center">暂无对话历史</p>
              <p className="text-sm text-center mt-2">点击"新对话"开始聊天</p>
            </div>
          ) : (
            <div className="space-y-2">
              {displayedConversations.map((conversation) => (
                <div
                  key={conversation.id}
                  className={`group relative p-3 rounded-lg border cursor-pointer transition-all hover:bg-accent ${
                    currentConversationId === conversation.id
                      ? 'bg-accent border-primary'
                      : 'hover:border-border'
                  }`}
                  onClick={() => onSelectConversation(conversation.id, conversation.chatMode)}
                >
                  <div className="flex items-start justify-between">
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-1">
                        <h4 className="font-medium text-sm truncate">
                          {conversation.title}
                        </h4>
                        {conversation.chatMode === 'agent' && (
                          <span className="inline-flex items-center px-2 py-1 rounded-full text-xs bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200">
                            🤖 智能体
                          </span>
                        )}
                        <span className="inline-flex items-center px-2 py-1 rounded-full text-xs bg-secondary text-secondary-foreground">
                          {conversation.messageCount}
                        </span>
                      </div>
                      <p className="text-xs text-muted-foreground truncate mb-2">
                        {conversation.lastMessage}
                      </p>
                      <div className="flex items-center gap-1 text-xs text-muted-foreground">
                        <Calendar className="w-3 h-3" />
                        {formatTimestamp(conversation.timestamp)}
                      </div>
                    </div>
                    
                    <Button
                      variant="ghost"
                      size="sm"
                      className="opacity-0 group-hover:opacity-100 transition-opacity ml-2 h-8 w-8 p-0"
                      onClick={(e) => {
                        e.stopPropagation()
                        deleteConversation(conversation.id)
                      }}
                    >
                      <Trash2 className="w-4 h-4 text-destructive" />
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
        
        {hasMore && !isLoading && (
          <div className="px-4 pb-4 pt-2 border-t">
            <Button
              variant="outline"
              size="sm"
              className="w-full flex items-center gap-2"
              onClick={loadMore}
            >
              <ChevronDown className="w-4 h-4" />
              加载更多 ({conversations.length - displayedConversations.length} 条)
            </Button>
          </div>
        )}
      </CardContent>
    </Card>
  )
}

// 导出ref类型供父组件使用
export interface ConversationListRef {
  addOrUpdateConversation: (conversationId: string, lastMessage: string) => void
}